<?php

/**
 * 用户列表
 *
 * @author JiangJian <silverd@sohu.com>
 * @copyright 2011-2012 xiangle.com
 * $Id: Admin.php 162 2012-11-09 04:04:30Z Jun.Lu.726@gmail.com $
 * @version    2012-02-15  ::  JiangJian  ::  Create File
 */
class Controller_System_Admin extends Controller_Abstract
{

    private $_admin;

    public function init()
    {
        parent::init();
        $this->_admin = Model('System_Admin');
    }

    /**
     * 用户列表
     */
    public function indexAction()
    {
        // 列表分页
        $pageSize = 20;
        $page     = max(1, intval($this->get('page')));
        $start    = ($page - 1 ) * $pageSize;

        // 搜索参数
        $params = array();
        $whereSql = '1';

        // 赋初值
        $list      = $multipage = '';

        // 按城市搜
        $cityId = intval($this->get('city_id'));
        if ($cityId > 0) {
            $whereSql .= " AND city_id = '{$cityId}'";
            $params['city_id'] = $cityId;
        }

        // 按邮箱搜
        $email = trim($this->get('email'));
        if ($email) {
            $whereSql .= " AND email LIKE '%{$email}%'";
            $params['email'] = $email;
        }

        // 按用户名搜
        $adminName = trim($this->get('admin_name'));
        if ($adminName) {
            $whereSql .= " AND admin_name LIKE '%{$adminName}%'";
            $params['admin_name'] = $adminName;
        }

        // 按角色搜
        $roleId = trim($this->get('role_id'));
        if ($roleId) {
            $whereSql .= " AND role_id = '{$roleId}'";
            $params['role_id'] = $roleId;
        }

        // 查询
        $count = $this->_admin->count($whereSql);
        if ($count) {
            $list      = $this->_admin->findByPage($whereSql, $start, $pageSize);
            $multipage = Com_Pager::admincp($count, $pageSize, $page, '/_system/admin/', $params);
        }

        $this->assign(array(
            'params'    => $params,
            'count'     => $count,
            'list'      => $list,
            'multipage' => $multipage,
        ));
        //$this->render('system/admin_list');
    }

    /**
     * 添加用户
     */
    public function addAction()
    {
        // 提交前
        if (!$this->isPost()) {

            $this->assign('action', 'add');
            //$this->render('system/admin_cu');
            // 提交后
        } else {

            $data = $this->getPost();

            // 检查是否越级
            $this->_checkPermission($data['role_id'], -1, 'halt');

            $result = $this->_admin->add($data);
            if ($result !== true) {
                $this->alert($result, 'error', 'halt');
            }

            // 操作日志
            $message = "添加了一个新用户“{$data['admin_name']}”，同时启用了该用户";
            Model('System_OpLog')->add('ADD_USER', $message, $this->_authUser);

            $this->alert('添加用户成功', 'success', '/_system/admin');
        }
    }

    /**
     * 更新用户
     */
    public function updateAction()
    {
        $adminId = intval($this->get('admin_id'));
        if ($adminId < 1) {
            $this->alert('非法的用户id', 'error');
        }

        $theOne = $this->_admin->rowByPk($adminId);
        if (!$theOne) {
            $this->alert('用户信息不存在', 'error');
        }

        // 提交前
        if (!$this->isPost()) {

            // 检查是否越级
            $this->_checkPermission($theOne['role_id'], $adminId);

            $this->assign('theOne', $theOne);
            $this->assign('action', 'update');

            // 提交后
        } else {

            $data = $this->getPost();

            // 检查是否越级
            $this->_checkPermission($data['role_id'], $adminId, 'halt');

            $result = $this->_admin->updateOne($adminId, $data);
            if ($result !== true) {
                $this->alert($result, 'error', 'halt');
            }

            // 操作日志
            $message = "更新用户“{$data['admin_name']}”的信息";
            Model('System_OpLog')->add('UP_USER', $message, $this->_authUser);

            $this->alert('修改用户成功', 'success');
        }
    }

    /**
     * 删除用户
     */
    public function deleteAction()
    {
        $adminId = intval($this->get('admin_id'));
        if ($adminId < 1) {
            $this->alert('非法的用户id', 'error');
        }

        $theOne = $this->_admin->rowByPk($adminId);
        if (!$theOne) {
            $this->alert('用户信息不存在', 'error');
        }

        // 检查是否越级
        $this->_checkPermission($theOne['role_id'], $theOne['admin_id']);

        if (!$this->_admin->deleteByPk($adminId)) {
            $this->alert('删除用户失败', 'error');
        }

        // 操作日志
        $message = "删除了用户“{$theOne['admin_name']}”";
        Model('System_OpLog')->add('DEL_USER', $message, $this->_authUser);

        $this->alert('删除用户成功', 'success');
    }

    /**
     * 启用、禁用用户
     */
    public function changeStatusAction()
    {
        $id = intval($this->get('id'));
        if ($id < 1) {
            exit('非法');
        }

        $theOne = $this->_admin->rowByPk($id);
        if (!$theOne) {
            exit('不存在');
        }

        // 检查是否越级
        $this->_checkPermission($theOne['role_id'], $theOne['admin_id']);

        $status = intval($this->get('status')) ? 1 : 0;
        if (!$this->_admin->update(array('status' => $status), array('admin_id' => $id))) {
            exit('失败');
        }

        // 操作日志
        $message = ($status ? '启用' : '禁用' ) . "了用户“{$theOne['admin_name']}”";
        Model('System_OpLog')->add(($status ? 'START_USER' : 'FORBID_USER'), $message, $this->_authUser);

        // 重新输出按钮
        exit(Helper_CPanel::ajaxStatusLink('/_system/admin/change-status', $id, $status));
    }

    /**
     * 检查是否越级
     *
     * @param int $targetRoleId
     * @param int $targetAdminId
     * @param string $url
     * @return bool
     */
    protected function _checkPermission($targetRoleId, $targetAdminId, $url = '')
    {
        // root 无限制
        if ($this->_authUser['admin_id'] == 1) {
            return true;
        }

        // 根用户不允许被编辑；只能编辑权限比自己小的用户（对方角色ID比自己大）
        if ($targetAdminId == 1 || $targetRoleId < $this->_authUser['role_id']) {

            // Ajax Output
            if ($this->_request->isXmlHttpRequest()) {
                exit('denied');
            }

            $this->alert('对不起，您无权进行此项操作，请返回', 'error', $url);
        }
    }

}